<!-- 搜索表单 -->
<template>
  <a-card :bordered="false">
    <!-- 搜索表单 -->
    <a-form :label-col="{ md: { span: 6 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }">
      <a-row>
        <a-col :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-item label="名称">
            <a-auto-complete v-model:value="oceanWhere.customer" :options="customerOptions" placeholder="请输入名称"
              @select="customer_onSelect2" @search="customer_onSearch" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-item label="提单号">
            <a-input v-model:value.trim="oceanWhere.billOfLading" placeholder="请输入提单号" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-item label="开船日期">
            <a-range-picker v-model:value="sailingDate2" :format="YYYY - MM - DD" placeholder="" class="ele-fluid" />
          </a-form-item>
        </a-col>
        <a-col :lg="6" :md="12" :sm="24" :xs="24" >
          <a-form-item :wrapper-col="{ span: 24 }">
            <em></em>
            <a-space>
              <a-button type="primary" @click="oceanReload">查询</a-button>
              <a-button @click="oceanReset">重置</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <!-- 表格 -->
    <ele-pro-table ref="oceanTableRef" row-key="id" :columns="columns" @update:selection="oceanTableOnSelectionChange"
      :customRow="oceanTableRowClick" v-model:current="oceanCurrent" :datasource="datasource" :scroll="{ x: 2500 }"
      cacheKey="ocean">
      <template #toolbar>
        <a-space>
          <a-button type="primary" @click="oceanOpenEdit()" v-any-permission="['order:ocean:save']">
            <template #icon>
              <plus-outlined />
            </template>
            <span>下单</span>
          </a-button>
          <a-button v-if="oceanCurrent.id > 0" type="primary" @click="exportOcean()">
            <template #icon>
              <plus-outlined />
            </template>
            <span>海运账单</span>
          </a-button>
          <a-button @click="containOceanApplyBtn()" style="color: #4e72b8;">
            <template #icon>
              <plus-outlined />
            </template>
            <span>报关关联</span>
          </a-button>
          <div v-if="oceanCurrent.billOfLading != ''">
            <a-tag color="purple" v-if="oceanCurrent.containbillId != 0 && oceanCurrent.containbillId != null">拖车</a-tag>
            <a-tag color="cyan" v-if="oceanCurrent.applyId != 0 && oceanCurrent.applyLading != null">报关</a-tag>
          </div>
        </a-space>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'annex'">
          <template v-if="record.annex != '' && record.annex != null && record.annex.length > 3">
            <template v-for="(item2, index2) in JSON.parse(record.annex)" :key="index2">
              <div class="annex" @click="openFile(item2.url)">{{ index2 + 1 }}. {{ item2.name }}</div>
            </template>
          </template>
          <template v-else>
            <div></div>
          </template>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="oceanOpenEdit(record)" v-any-permission="['order:ocean:update']">修改</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定要删除此项吗？" @confirm="oceanRemove(record)">
              <a class="ele-text-danger" v-any-permission="['order:ocean:remove']">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </ele-pro-table>
  </a-card>
  <!-- 海运添加、修改弹窗 -->
  <ele-modal :width="460" v-model:visible="oceanVisible_modal" :confirm-loading="loading"
    :title="oceanIsUpdate ? '修改海运' : '新建海运'" :body-style="{ paddingBottom: '8px' }" @ok="oceanSave" :maskClosable="false">
    <a-form ref="oceanFormRef" :model="oceanForm" :rules="oceanRules" :label-col="{ md: { span: 7 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
      <a-form-item label="客户名称" name="customer_val">
        <a-auto-complete v-model:value="oceanForm.customer_val" :options="customerOptions" placeholder="请输入客户名称"
          @select="customer_onSelect" @search="customer_onSearch" @blur="customer_blur" allow-clear />
      </a-form-item>
      <a-form-item label="船公司" name="shippingCompany">
        <a-select v-model:value="oceanForm.shippingCompany" show-search placeholder="请输入船公司"
          :options="shippingCompany_options" :filter-option="shippingCompany_filter"></a-select>
      </a-form-item>
      <a-form-item label="订舱代理" name="bookingAgent">
        <a-auto-complete v-model:value="oceanForm.bookingAgent_val" :options="bookingAgentOptions" placeholder="请输入客户名称"
          @select="bookingAgent_onSelect" @search="bookingAgent_onSearch" @blur="bookingAgent_blur" allow-clear />
      </a-form-item>
      <a-form-item label="开船日期" name="sailingDate">
        <a-date-picker v-model:value="oceanForm.sailingDate" valueFormat="YYYY-MM-DD" placeholder="请输入开船日期"
          class="ele-fluid" allow-clear />
      </a-form-item>
      <a-form-item label="提单号" name="billOfLading">
        <a-input allow-clear :maxlength="200" placeholder="请输入提单号" v-model:value="oceanForm.billOfLading"
          autocomplete="off" />
      </a-form-item>
      <a-form-item label="箱型" name="boxType">
        <a-select v-model:value="oceanForm.boxType" show-search placeholder="请输入箱型" :options="boxType_options"
          :filter-option="boxType_filter" allow-clear></a-select>
      </a-form-item>
      <a-form-item label="航次" name="voyage">
        <a-input allow-clear :maxlength="200" placeholder="请输入航次" v-model:value="oceanForm.voyage" autocomplete="off" />
      </a-form-item>
      <a-form-item label="船名" name="vessel">
        <a-input allow-clear :maxlength="200" placeholder="请输入船名" v-model:value="oceanForm.vessel" autocomplete="off" />
      </a-form-item>
      <a-form-item label="起运港" name="portOfDeparture">
        <a-select v-model:value="oceanForm.portOfDeparture" show-search placeholder="请输入起运港"
          :options="portOfDeparture_options" :filter-option="portOfDeparture_filter" allow-clear></a-select>
      </a-form-item>
      <a-form-item label="目的港" name="portOfDestination">
        <a-select v-model:value="oceanForm.portOfDestination" show-search placeholder="请输入目的港"
          :options="portOfDestination_options" :filter-option="portOfDestination_filter" allow-clear></a-select>
      </a-form-item>
      <a-form-item label="签单方式" name="signing">
        <a-select v-model:value="oceanForm.signing">
          <a-select-option value="正本">正本</a-select-option>
          <a-select-option value="电放">电放</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="封号" name="sealNo">
        <a-input allow-clear :maxlength="200" placeholder="请输入封号" v-model:value="oceanForm.sealNo" autocomplete="off" />
      </a-form-item>
      <a-form-item label="箱号" name="boxNo">
        <a-input allow-clear :maxlength="200" placeholder="请输入箱号" v-model:value="oceanForm.boxNo" autocomplete="off" />
      </a-form-item>
      <a-form-item label="附件" name="annex">
        <a-upload-dragger v-model:file-list="oceanForm.annexFilelist" @remove="annexUploadFilesRemove"
          :customRequest="annexUploadFiles" :multiple="true">
          <p class="ant-upload-drag-icon">
            <inbox-outlined></inbox-outlined>
          </p>
          <p class="ant-upload-text">Click or drag file to this area to upload</p>
          <p class="ant-upload-hint">
            Support for a single or bulk upload. Strictly prohibit from uploading company data or other
            band files
          </p>
        </a-upload-dragger>
      </a-form-item>
    </a-form>
  </ele-modal>
  <!-- 拖车海运报关 关联表 弹窗 -->
  <ele-modal :width="1300" v-model:visible="containOceanApply_modal" :confirm-loading="loading" title="拖车海运报关 关联表"
    :body-style="{ paddingBottom: '8px' }" :maskClosable="false" :move-out="true" footer="" :resizable="false"
    position="center">
    <ContainerOceanApply ref="containOceanApplyComp"></ContainerOceanApply>
  </ele-modal>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue';
import { toDateString } from 'ele-admin-pro';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import { listSettings } from '@/api/order/settings';
import { listCustomersSel } from '@/api/order/customer';
import { pageOcean, removeOcean, addOcean, updateOcean } from '@/api/order/ocean';

import { API_BASE_URL, TOKEN_HEADER_NAME } from '@/config/setting';
import { TIME_OUT } from '@/config/damon';
import { fileUpload } from '@/api/file';
import { getToken } from '@/utils/token-util';

import ContainerOceanApply from '@/views/order/containerBill/components/containerOceanApply.vue';

function openFile(op) {
  // 打开新窗口
  window.open(API_BASE_URL + '/file/' + op, '_blank');
}


// 表格实例
const oceanTableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (oceanTableRef.value?.tableIndex ?? 0)
  },
  {
    title: '附件',
    dataIndex: 'annex',
    key: 'annex',
    width: 150,
    // sorter: true
  },
  {
    title: '客户名称',
    dataIndex: 'customer',
    key: 'customer',
    // sorter: true
  },
  {
    title: '船公司',
    dataIndex: 'shippingCompany',
    key: 'shippingCompany',
    // sorter: true
  },
  {
    title: '订舱代理',
    dataIndex: 'bookingAgent',
    key: 'bookingAgent',
    // sorter: true
  },
  {
    title: '箱型',
    dataIndex: 'boxType',
    key: 'boxType',
    // sorter: true
  },
  {
    title: '航次',
    dataIndex: 'voyage',
    key: 'voyage',
    // sorter: true
  },
  {
    title: '船名',
    dataIndex: 'vessel',
    key: 'vessel',
    // sorter: true
  },
  {
    title: '提单号',
    dataIndex: 'billOfLading',
    key: 'billOfLading',
    // sorter: true
  },
  {
    title: '起运港',
    dataIndex: 'portOfDeparture',
    key: 'portOfDeparture',
    // sorter: true
  },
  {
    title: '目的港',
    dataIndex: 'portOfDestination',
    key: 'portOfDestination',
    // sorter: true
  },
  {
    title: '开船日期',
    dataIndex: 'sailingDate',
    key: 'sailingDate',
    // sorter: true
  },
  {
    title: '签单方式',
    dataIndex: 'signing',
    key: 'signing',
    // sorter: true
  },
  {
    title: '封号',
    dataIndex: 'sealNo',
    key: 'sealNo',
    // sorter: true
  },
  {
    title: '箱号',
    dataIndex: 'boxNo',
    key: 'boxNo',
    // sorter: true
  },
  {
    title: '业务员',
    dataIndex: 'salesman',
    key: 'salesman',
    // sorter: true
  },
  {
    title: '操作',
    dataIndex: 'operater',
    key: 'operater',
    // sorter: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '创建人',
    dataIndex: 'createName',
    key: 'createName',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

// 表单数据
const { form: oceanWhere, resetFields } = useFormData({
  username: '',
  sex: undefined,
  date1: '',
  date2: '',
});
let sailingDate2 = ref([
  dayjs().subtract(1, 'day'),
  dayjs().add(1, 'day'),
  // dayjs().add(2, 'month'),
])



let datasource_index = true
// 表格数据源
const datasource = ({ page, limit, where, orders }) => {
  if (datasource_index) {
    where.date1 = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
    where.date2 = dayjs().add(1, 'day').format('YYYY-MM-DD')
  }
  return pageOcean({ ...where, ...orders, page, limit });
};

/* 搜索 */
const oceanReload = () => {
  datasource_index = false
  oceanTableRef?.value?.reload({ page: 1, where: oceanWhere });
};

/* 搜索 */
const oceanReload2 = () => {
  oceanTableRef?.value?.reload();
};

let where_timeout = 0
watch(() => oceanWhere, (val) => {
  clearTimeout(where_timeout)
  where_timeout = setTimeout(() => {
    oceanReload()
  }, TIME_OUT);
},
  { deep: true }
)
watch([() => sailingDate2.value], (val) => {
  clearTimeout(where_timeout)
  where_timeout = setTimeout(() => {
    if (sailingDate2.value == null) {
      sailingDate2.value = []
    }
    if (sailingDate2.value.length > 0) {
      oceanWhere.date1 = dayjs(sailingDate2.value[0]).format('YYYY-MM-DD')
      oceanWhere.date2 = dayjs(sailingDate2.value[1]).format('YYYY-MM-DD')
    } else {
      oceanWhere.date1 = ''
      oceanWhere.date2 = ''
    }
  }, TIME_OUT);
},
  { deep: true }
)
/*  重置 */
const oceanReset = () => {
  resetFields();
  oceanReload();
};

let oceanTableRowClick = (record, index) => {
  return {
    onClick: (event) => {
      oceanCurrent.value = record
      sendBillSelect()
    },
  }
}
let oceanTableOnSelectionChange = (current_options) => {
  oceanCurrent.value = current_options[0];
  sendBillSelect()
};
let sendBillSelect = () => {
  // //oceanFeeComp
  emit('oceanIdSelect', {
    'oceanId': oceanCurrent.value.id,
    'invoice': {
      'company': oceanCurrent.value.customer,
      'bookingAgent': oceanCurrent.value.bookingAgent,
    }
  });
}
const emit = defineEmits(['oceanIdSelect'])

/* 删除单个 */
const oceanRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeOcean(record.id).then((msg) => {
    hide();
    message.success(msg);
    oceanReload2();
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};

// 当前选中数据
const oceanCurrent = ref({ 'billOfLading': '', id: 0 });

// 弹窗是否打开
const oceanVisible_modal = ref(false);

// 弹窗是否打开
const containOceanApply_modal = ref(false);

// 是否是修改
const oceanIsUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const oceanFormRef = ref(null);

// 表单数据
const { form: oceanForm, resetFields: oceanResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
  annex: '',
});

// 表单验证规则
const oceanRules = reactive({
  name: [
    {
      required: true,
      message: '请输入名称',
      type: 'string',
    }
  ],
});

let time_out = 0
function exportOcean() {
  clearTimeout(time_out)
  time_out = setTimeout(() => {
    exportOcean_real()
  }, 300);

}
function exportOcean_real() {
  let dataStr = '?id=' + oceanCurrent.value.id
  let url = API_BASE_URL + '/order/ocean/exportsOcean' + dataStr
  var xhr = new XMLHttpRequest();
  xhr.open("get", url, true); // get、post都可
  xhr.responseType = "blob";  // 转换流
  xhr.setRequestHeader(TOKEN_HEADER_NAME, getToken()); // token键值对
  xhr.onload = function () {
    if (this.status == 200) {
      var blob = this.response;
      var a = document.createElement("a")
      var url = window.URL.createObjectURL(blob)
      a.href = url
      a.download = "海运费用" + oceanCurrent.value.customer + oceanCurrent.value.billOfLading + ".xlsx"  // 文件名
    }
    a.click()
    window.URL.revokeObjectURL(url)
  }
  xhr.send();
  message.success('导出成功');
}

let containOceanApplyComp = ref(null)
const containOceanApplyBtn = () => {
  containOceanApply_modal.value = true;
  setTimeout(() => {
    // containerBillCurrent.value.son_type = 'containerBill'
    containOceanApplyComp.value.removeContaiOceanApplyFormData()
    // containOceanApplyComp.value.onContainerBillSelect(containerBillCurrent.value)
  }, 1000);
}

//防止重复刷新
//客户下拉列表
const customerOptions = ref([]);
let customer_m_timeout = 0
const customer_onSearch = searchText => {
  clearTimeout(customer_m_timeout)
  customer_m_timeout = setTimeout(() => {
    listCustomersSel({ 'name': searchText, type: '货代' }).then(msg => {
      customerOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const customer_onSelect = (value2, option2) => {
  // let a = customerOptions.value.find((item)=> {return item.value=value})
  oceanForm.customer_val = option2.label
  oceanForm.customer = option2.label
  oceanForm.customerId = option2.value
};
const customer_blur = () => {
  oceanForm.customer_val = oceanForm.customer
};
//搜索客户条件
const customer_onSelect2 = (value2, option2) => {
  // let a = customerOptions.value.find((item)=> {return item.value=value})
  oceanWhere.customer = option2.label
};
//订舱代理下拉
const bookingAgentOptions = ref([]);
const bookingAgent_onSearch = searchText => {
  clearTimeout(customer_m_timeout)
  customer_m_timeout = setTimeout(() => {
    listCustomersSel({ 'name': searchText, type: '订舱代理' }).then(msg => {
      bookingAgentOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const bookingAgent_onSelect = (value2, option2) => {
  // let a = bookingAgentOptions.value.find((item)=> {return item.value=value})
  oceanForm.bookingAgent_val = option2.label
  oceanForm.bookingAgent = option2.label
  oceanForm.bookingAgentId = option2.value
};
const bookingAgent_blur = () => {
  oceanForm.bookingAgent_val = oceanForm.bookingAgent
};
//船公司下拉
let shippingCompany_options = ref([])
listSettings({ 'typeM': 'ship' }).then(msg => {
  shippingCompany_options.value = msg
}).catch((e) => {
})
const shippingCompany_filter = (input, option) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
//箱型下拉
let boxType_options = ref([])
listSettings({ 'typeM': 'box_type' }).then(msg => {
  boxType_options.value = msg
}).catch((e) => {
})
const boxType_filter = (input, option) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
//起运港下拉
let portOfDeparture_options = ref([])
listSettings({ 'typeM': 'ocean_dock_type' }).then(msg => {
  portOfDeparture_options.value = msg
}).catch((e) => {
})
const portOfDeparture_filter = (input, option) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
//目的港下拉
let portOfDestination_options = ref([])
listSettings({ 'typeM': 'ocean_dock_type' }).then(msg => {
  portOfDestination_options.value = msg
}).catch((e) => {
})
const portOfDestination_filter = (input, option) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
//附件上传
function annexUploadFiles(info) {
  //开始真正上传
  //上传接口
  //调用公共上传方法
  fileUpload({ 'file': info.file, 'path2': 'chf_ocean' }).then((msg) => {
    const upload_file_list_tmp_arr = {}
    upload_file_list_tmp_arr['uid'] = info.file.uid
    upload_file_list_tmp_arr['name'] = info.file.name
    upload_file_list_tmp_arr['status'] = 'done'
    upload_file_list_tmp_arr['url'] = msg.data.path + "?path2=chf_ocean"
    let arr = (oceanForm.annex == '' || oceanForm.annex == null) ? [] : JSON.parse(oceanForm.annex)
    arr.push(upload_file_list_tmp_arr)
    oceanForm.annex = JSON.stringify(arr)
    oceanForm.annexFilelist == undefined || oceanForm.annexFilelist.map(element => {
      element.status = 'done'
      element.url = API_BASE_URL + '/file/' + element.url
    })
    message.success('上传成功');

  }).catch((e) => {
    message.error(e.message);
  });
}
let annexUploadFilesRemove = info => {
  let arr = JSON.parse(form.annex)
  arr.splice(arr.findIndex(item => item.uid == info.uid), 1)
  form.annex = JSON.stringify(arr)
}
const fileUploadOpenForm = (record) => {
  oceanForm.annexFilelist = []
  if (record != undefined) {
    if (record.annex != '') {
      oceanForm.annexFilelist = [...JSON.parse(record.annex)]
    }
  }
}

/* 打开编辑弹窗 */
const oceanOpenEdit = (record) => {
  oceanResetFormFields();
  oceanFormRef.value?.clearValidate();
  oceanCurrent.value = record ?? {};
  oceanVisible_modal.value = true;
  Object.assign(oceanForm, record ?? {});
  oceanIsUpdate.value = !!record?? {};
  oceanForm.customer_val = ''
  oceanForm.bookingAgent_val = ''
  if (record != undefined) {
    oceanForm.customer_val = record.customer
    oceanForm.bookingAgent_val = record.bookingAgent
  }
  fileUploadOpenForm(record)
};

/* 保存编辑 */
const oceanSave = () => {
  if (!oceanFormRef.value) {
    return;
  }
  oceanFormRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = oceanIsUpdate.value ? updateOcean : addOcean;
    saveOrUpdate(oceanForm).then((msg) => {
      loading.value = false;
      message.success(msg);
      oceanVisible_modal.value = false;
      oceanReload2();
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};
</script>

<style lang="less" scoped>
.annex {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;

  cursor: pointer;
  color: #426ab3;
}
</style>
